<template>
  <el-card shadow="always" :body-style="{ padding: '20px' }">
    <el-form label-width="80px" :inline="true" :disabled="props.disabled">
      <el-form-item label="一级列表">
        <el-select
          placeholder="请选择一级列表"
          clearable
          filterable
          v-model="(category1Id as number)"
          @change="category1change"
        >
          <el-option
            :label="category1.name"
            v-for="category1 in category1List"
            :key="category1.id"
            :value="category1.id"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="二级列表">
        <el-select
          placeholder="请选择二级列表"
          clearable
          filterable
          v-model="(category2Id as number)"
          @change="category2change"
        >
          <el-option
            :label="category2.name"
            v-for="category2 in category2List"
            :key="category2.id"
            :value="category2.id"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="一级列表">
        <el-select
          placeholder="请选择二级列表"
          clearable
          filterable
          v-model="(category3Id as number)"
        >
          <el-option
            :label="category3.name"
            v-for="category3 in category3List"
            :key="category3.id"
            :value="category3.id"
          ></el-option>
        </el-select>
      </el-form-item>
    </el-form>
  </el-card>
</template>

<script lang="ts">
import { defineComponent } from "vue";

export default defineComponent({
  name: "Category",
});
</script>

<script setup lang="ts">
import useCategroyStore from "@/stores/category";
import { storeToRefs } from "pinia";
import { onMounted } from "vue";

//三级列表 pinia
const categoryStore = useCategroyStore();

onMounted(() => {
  // 获取一级列表数据
  categoryStore.getCategory1List();
});

// props
const props = defineProps<{
  disabled: boolean;
}>();

// 获取三级分类pinia中的数据
const {
  category1List,
  category1Id,
  category2List,
  category2Id,
  category3List,
  category3Id,
} = storeToRefs(categoryStore);

// 改变一级列表的事件
const category1change = () => {
  // 重置二级三级列表选择及数据
  category2Id.value = null;
  category2List.value = [];
  category3Id.value = null;
  category3List.value = [];
  // 判断是否有1id  没有则不请求
  if (!category1Id.value) return;
  // 获取二级列表数据
  categoryStore.getCategory2List();
};

// 改变二级列表的事件
const category2change = () => {
  // 重置三级列表选择及数据
  category3Id.value = null;
  category3List.value = [];

  // 判断是否有2id  没有则不请求
  if (!category2Id.value) return;

  // 获取三级列表数据
  categoryStore.getCategory3List();
};
</script>

<style scoped lang="scss"></style>
